Your interesting code tricks/ conventions? [closed]

Posted by Paul on Programmers See other posts from Programmers or by Paul
Published on 2011-06-21T15:11:46Z Indexed on 2011/06/21 16:30 UTC
Read the original article Hit count: 326

What interesting conventions, rules, tricks do you use in your code? Preferably some that are not so popular so that the rest of us would find them as novelties. :) Here's some of mine...

Input and output parameters

This applies to C++ and other languages that have both references and pointers. This is the convention: input parameters are always passed by value or const reference; output parameters are always passed by pointer.

This way I'm able to see at a glance, directly from the function call, what parameters might get modified by the function:

Inspiration: Old C code

int a = 6, b = 7, sum = 0;
calculateSum(a, b, &sum);

Ordering of headers

My typical source file begins like this (see code below). The reason I put the matching header first is because, in case that header is not self-sufficient (I forgot to include some necessary library, or forgot to forward declare some type or function), a compiler error will occur.

// Matching header
#include "example.h"

// Standard libraries
#include <string>
...

Setter functions

Sometimes I find that I need to set multiple properties of an object all at once (like when I just constructed it and I need to initialize it). To reduce the amount of typing and, in some cases, improve readability, I decided to make my setters chainable:

Inspiration: Builder pattern

class Employee
{
  public:
    Employee& name(const std::string& name);
    Employee& salary(double salary);

  private:
    std::string name_;
    double salary_;
};

Employee bob;
bob.name("William Smith").salary(500.00);

Maybe in this particular case it could have been just as well done in the constructor. But for Real WorldTM applications, classes would have lots more fields that should be set to appropriate values and it becomes unmaintainable to do it in the constructor.

So what about you? What personal tips and tricks would you like to share?

© Programmers or respective owner

Related posts about tips-and-tricks

Related posts about conventions